<template>
  <div>
    <HeaderView></HeaderView>
    <ListView>
      <template v-slot:list>
        <div class="operate">
          <div class="from-box">
            <el-form :inline="true" :model="queryNameForm" class="demo-form-inline">
              <el-form-item label="艺术家名称">
                <el-input size="small" clearable v-model="queryNameForm.name" placeholder="请输入艺术家名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button size="small" type="primary" @click="queryArtist"><i class="el-icon-search"></i>查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="add-box">
            <el-button size="small" @click="addWin = true" type="success"><i class="el-icon-plus"></i> 增添</el-button>
          </div>
        </div>

        <!--表格-->
        <el-table
            :data="tableData"
            border
            style="width: 100%"
            max-height="600">
          <el-table-column
              prop="name"
              label="艺术家名称"
              width="241">
          </el-table-column>
          <el-table-column
              prop="description"
              label="描述"
              width="241">
          </el-table-column>
          <el-table-column
              prop="picUrl"
              label="艺术家图片"
              width="130">
            <template slot-scope="{row}">
              <div v-if="row.picUrl==='' || row.picUrl.substring(0,33)!==tableImageUrl" class="el-image__error">加载失败
              </div>
              <div v-else class="el_image">
                <img :src="row.picUrl" alt="加载中...">
              </div>
            </template>
          </el-table-column>
          <el-table-column
              prop="status"
              label="状态"
              width="130">
            <template slot-scope="{row}">
              <el-tag type="success" plain>{{ row.status === 1 ? '正常' : '异常' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
              prop="createTime"
              label="创建时间"
              width="220">
            <template slot-scope="{row}">
              {{ formatDate(new Date(row.createTime)) }}
            </template>
          </el-table-column>
          <el-table-column
              prop="updateTime"
              label="更新时间"
              width="220">
            <template slot-scope="{row}">
              {{ formatDate(new Date(row.createTime)) }}
            </template>
          </el-table-column>
          <el-table-column
              fixed="right"
              label="操作"
              width="180">
            <template slot-scope="scope">
              <el-button
                  plain
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click="handleEdit(scope.row)">编辑
              </el-button>
              <el-button
                  plain
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  @click="handleDelete(scope.row)">删除
              </el-button>
            </template>

          </el-table-column>
        </el-table>
        <!--分页-->
        <div class="block">
          <el-pagination
              background
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="10"
              layout="total, sizes, prev, pager, next, jumper"
              :total=total>
          </el-pagination>
        </div>
      </template>

    </ListView>

    <!--添加艺术家-->
    <el-drawer
        title="新增艺术家"
        :visible.sync="addWin"
        direction="rtl"
        size="40%"
        :before-close="handleClose">
      <div class="demo-drawer__content">
        <el-form :model="addForm" status-icon :rules="rules" ref="addForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="专辑名" prop="name">
            <el-input type="text" v-model="addForm.name" placeholder="请输入专辑名"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}" v-model="addForm.description"
                      placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="艺术家图片" prop="picUrl">
            <div class="image-container" @mouseenter="showButton" @mouseleave="hideButton">
              <el-image v-if="picUrl" :src="picUrl" class="avatar"></el-image>
              <div class="buttons">
                <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary"
                           @click.stop="upload">图库上传
                </el-button>
                <el-upload :http-request="fileRequest"
                           action="" ref="upload">
                  <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary">本地上传
                  </el-button>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="button-box">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="handleAddSubmit" :loading="loading">
            {{ loading ? '添加中 ...' : '确 定' }}
          </el-button>
        </div>

      </div>
    </el-drawer>
    <!--编辑艺术家-->
    <el-drawer
        title="编辑用户"
        :visible.sync="editWin"
        direction="rtl"
        trigger
        size="40%"
        tip="本地文件"
        :before-close="handleClose">
      <div class="demo-drawer__content">
        <el-form :model="editForm" status-icon :rules="rules" ref="editForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="专辑名" prop="name">
            <el-input type="text" v-model="editForm.name" placeholder="请输入专辑名"></el-input>
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}" v-model="editForm.description"
                      placeholder="请输入"></el-input>
          </el-form-item>
          <el-form-item label="艺术家图片" prop="picUrl">
            <div class="image-container" @mouseenter="showButton" @mouseleave="hideButton">
              <el-image v-if="picUrl" :src="picUrl"></el-image>
              <div class="buttons">
                <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary"
                           @click.stop="upload">图库上传
                </el-button>
                <el-upload :http-request="fileRequest"
                           action="" ref="upload">
                  <el-button style="margin: 5px" v-if="showButtons" size="mini" type="primary">本地上传
                  </el-button>
                </el-upload>
              </div>
            </div>
          </el-form-item>
        </el-form>
        <div class="button-box">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="handleEditSubmit" :loading="loading">
            {{ loading ? '修改中 ...' : '确 定' }}
          </el-button>
        </div>

      </div>
    </el-drawer>

    <!--    图库-->
    <el-dialog title="上传文件"
               :visible.sync="fileWin" width="1000px">
      <div class="dialog-height">
        <div class="img-box">
          <el-radio-group v-model="selectedIndex" size="small">
            <el-radio-button :label="index" v-for="(item, index) in fileList" :key="index">
              <el-image @click="selectImage(item.picUrl)" style="width: 200px; height: 200px"
                        :src="item.picUrl"></el-image>
            </el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <el-button @click="fileWin = false">取 消</el-button>
      <el-button @click="fileWin = false" type="primary">确 定</el-button>
    </el-dialog>
  </div>
</template>

<script>
import HeaderView from "@/views/layout/headerView.vue";
import ListView from "@/views/layout/listView.vue";
import {getArtistList, addArtist, updateArtist, deleteArtist, getResource, uploadResource} from "@/api/common";
import {completionUrl, splitImageUrl} from "@/utils/common";
import {formatDate} from "@/utils/dateTimeFormatter";

export default {
  components: {ListView, HeaderView},
  data() {
    return {
      // 添加用户侧边框
      addWin: false,
      loading: false,
      // 修改用户侧边框
      editWin: false,

      addForm: {
        name: '',
        description: '',
        picUrl: '',
      },
      editForm: {
        name: '',
        description: '',
        picUrl: '',
      },
      rules: {
        name: [
          {required: true, message: '请输入艺术家名称', trigger: 'blur'},
        ],
        picUrl: [
          {required: true, message: '昵称不能为空', trigger: 'blur'},
        ],
      },

      // 文件
      fileWin: false,
      showButtons: true,
      picUrl: '',
      // 服务器图片
      fileList: [],
      selectedImageUrl: '',
      selectedIndex: null,

      // 表格数据
      tableData: [],
      // 校验表格图片地址
      tableImageUrl: 'http://dyw770.top:18080/resource/',

      // 分页
      page: 0,
      size: 10,
      total: 0,
      currentPage: 1,
      // 搜索
      queryNameForm: {
        name: '',
      },
    }
  },
  created() {
    this.reqArtistList()
  },
  methods: {
    formatDate,

    // 查询艺术家
    queryArtist() {
      this.reqArtistList()
    },
    // 获取艺术家列表
    reqArtistList() {
      const data = {
        page: this.page,
        size: this.size,
        orders: [
          {
            column: "1",
            asc: true
          }
        ],
        name: this.queryNameForm.name,
        description: "",
        offset: 0
      }
      getArtistList(data).then(response => {
        // console.log(response.data)
        response.data.data.records.forEach(item => {
          if (item.picUrl !== "") {
            item.picUrl = completionUrl(item.picUrl)
          }
        })
        this.tableData = response.data.data.records
        this.total = response.data.data.total
      })
    },

    // 添加
    // 提交表单数据
    handleAddSubmit() {
      this.$confirm('确认提交？')
          .then(() => {
            console.log("提交成功")
            this.loading = true

            addArtist(this.addForm).then(response => {
              console.log("response：", response)
            })
            setTimeout(() => {
              // 提交数据后清空表单
              this.$refs['addForm'].resetFields()
              // 重新请求 刷新
              this.reqArtistList()
              this.close()
            }, 1000)
          })
          .catch(() => {
            this.close()
            // this.cancelForm()
          });
    },

    // 点击编辑事件
    handleEdit(row) {
      this.editWin = true
      this.picUrl = row.picUrl
      this.editForm = row
    },
    // 编辑艺术家信息
    handleEditSubmit() {
      this.$confirm('确认提交？')
          .then(() => {
            console.log("提交成功")
            this.loading = true
            this.editForm.picUrl = splitImageUrl(this.picUrl)
            // 修改请求
            updateArtist(this.editForm.id, this.editForm).then(response => {
              console.log(response)
            })
            setTimeout(() => {
              // 提交数据后清空表单
              this.$refs['editForm'].resetFields()
              // 重新请求 刷新
              this.reqArtistList()
              this.close()
            }, 1000)
          })
          .catch(() => {
            this.close()
            // this.cancelForm()
          });
    },

    // 删除艺术家
    handleDelete(row) {
      const h = this.$createElement;
      this.$msgbox({
        title: '提示',
        message: h('p', null, '确定删除，是否继续？'),
        showCancelButton: true,
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            instance.confirmButtonText = '执行中...';
            setTimeout(() => {
              done();
              instance.confirmButtonLoading = false;
            }, 300);
          }
          done();
        }
      }).then(() => {
        // 删除请求
        deleteArtist(row.id)

        setTimeout(() => {
          this.$message({
            message: "操作成功",
            type: 'success'
          })
          // 重新请求 刷新
          this.reqArtistList()
        }, 500)

      }).catch(() => {
      })

    },

    // 服务器图片上传
    upload() {
      this.fileWin = true
      console.log("点击了图库")
      getResource('image').then(response => {
        console.log(response)
        response.data.data.forEach(item => {
          var picUrl = completionUrl(item)
          this.fileList.push({picUrl: picUrl})
        })
      })
    },
    // 本地图片上传
    fileRequest(f) {
      let file = f.file
      const formData = new FormData
      formData.append('file', file)
      //upload为上传的接口
      uploadResource('image', formData).then(res => {
        this.addForm.picUrl = res.data.data
        this.picUrl = completionUrl(res.data.data)
      });
    },
    selectImage(picUrl) {
      this.picUrl = picUrl
      this.addForm.picUrl = splitImageUrl(picUrl)
      this.editForm.picUrl = splitImageUrl(picUrl)
    },

    // 关闭表单
    handleClose() {
      this.$confirm('确认关闭？')
          .then(() => {
            console.log("已关闭")
            this.close()
          })
          .catch(() => {
          });
    },

    // 分页
    // 每页多少条数据
    handleSizeChange(val) {
      this.size = val
      this.reqArtistList()
    },
    // 当前页
    handleCurrentChange(val) {
      this.page = val
      this.reqArtistList()
    },

    // 关闭侧边栏
    close() {
      if (this.addWin) {
        this.addWin = !this.addWin
      }
      if (this.editWin) {
        this.editWin = !this.editWin
      }
      this.loading = false;
    },

    // 上传图片选择按钮
    showButton() {
      this.showButtons = true;
    },
    hideButton() {
      this.showButtons = false;
    },
  }
}
</script>
<style scoped lang="scss">
.dialog-height {
  height: 600px;
  overflow-y: auto;
}

.image-container {
  display: flex;
  flex-direction: column;
  width: 148px;
  height: 148px;
  border: 1px dotted skyblue;
  border-radius: 4px;
  position: relative;
  margin: 10px;
}

.buttons {
  position: absolute;
  display: flex;
  flex-direction: column;
  margin: 30px 30px;
}

.image-container:hover button {
  display: block;
}

img {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
}

// 表单
.demo-drawer__content {
  padding: 10px;
  margin: 10px;
}

// 表单按钮
.button-box {
  display: flex;
  flex-direction: row;
  justify-content: space-evenly;
}

// 表格图片
.el-image__error, .el_image {
  width: 90px;
  height: 90px;
}

// 分页
.block {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>